<?php

namespace App\Models\Business;

use App\Models\Region as RegionModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Business\Source as  SourceModel;
use App\Models\Admin\Admin as AdminModel;
use App\Models\Config as ConfigModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Business extends Model
{
    use HasFactory;

    use SoftDeletes;

    // 指定的数据表
    protected $table = 'business';

    // 自动写入时间戳
    public $timestamps = true;

    // 时间类型
    protected $dateFormat = 'U';

    // 自定义创建时间字段
    const CREATED_AT = 'createtime';

    // 软删除字段
    const DELETED_AT = 'deletetime';

    // 自定义更新时间字段
    const UPDATED_AT = null;

    protected $guarded = [];

    protected $appends = [
        'mobile_text',
        'region_text',
        'avatar_cdn',
        'sex_text',
        'deal_text',
        'auth_text'
    ];

    // 定义不存在字段
    public function getMobileTextAttribute()
    {
        return substr_replace($this->mobile,'****',3,4);
    }

    public function getRegionTextAttribute()
    {
        $province = RegionModel::where('code',$this->province)->value('name');
        $city = RegionModel::where('code',$this->city)->value('name');
        $district = RegionModel::where('code',$this->district)->value('name');
        
        $text = '';

        if($province)
        {
            $text = $province . '-';
        }

        if($city)
        {
            $text .= $city . '-';
        }

        if($district)
        {
            $text .= $district;
        }
    
        return $text;
    }

    public function getAvatarCdnAttribute()
    {
        $cdn = ConfigModel::where(['name' => 'url'])->value('value');

        $url = $cdn . '/stock/business/avatar';

        $avatar = httpRequest($url,['id' => $this->id]);

        return $avatar;
    }

    //增加新字段 sex_text
    public function getSexTextAttribute() 
    {
        $sexlist = [0 => '保密', 1 => '男', 2 => '女'];

        $gender = isset($this->gender) ? $this->gender : '';

        if($gender >= '0'){
            return $sexlist[$gender];
        }
        return;
    }

    public function getDealTextAttribute() 
    {
        $sexlist = [0 => '未成交', 1 => '已成交'];
        
        $deal = isset($this->deal) ? $this->deal : '';

        if($deal >= '0'){
            return $sexlist[$deal];
        } 
        return ;
       
    }

    public function getAuthTextAttribute() 
    {
        $sexlist = [0 => '未认证', 1 => '已认证'];
        
        $auth = isset($this->auth) ? $this->auth : '';

        if($auth >= '0'){
            return $sexlist[$auth];
        } 
        return ;
       
    }

    public function source()
    {
        return $this->belongsTo(SourceModel::class,'sourceid','id');
    }

    public function admin()
    {
        return $this->belongsTo(AdminModel::class,'adminid','id');
    }
}
